//
//  PlayerModel.m
//  GameModules
//
//  Created by hyc on 16/6/30.
//  Copyright © 2016年 hyc. All rights reserved.
//

#import "PlayerModel.h"

@implementation PlayerModel

@synthesize storedScores,currentPlayerID,storedScoresFilename;

- (id)init
{
    self = [super init];
    if (self) {
        currentPlayerID = [NSString stringWithFormat:@"%@", [GKLocalPlayer localPlayer].playerID];
        NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        storedScoresFilename = [[NSString alloc] initWithFormat:@"%@/%@.storedScores.plist",path, currentPlayerID];
        writeLock = [[NSLock alloc] init];
    }
    return self;
}



// Attempt to resubmit the scores.
- (void)resubmitStoredScores
{
    if (storedScores) {
        // Keeping an index prevents new entries to be added when the network is down
        int index = (int)[storedScores count] - 1;
        while( index >= 0 ) {
            GKScore * score = [storedScores objectAtIndex:index];
            [self submitScore:score];
            [storedScores removeObjectAtIndex:index];
            index--;
        }
        [self writeStoredScore];
    }
}

// Load stored scores from disk.
- (void)loadStoredScores
{
    NSArray *  unarchivedObj = [NSKeyedUnarchiver unarchiveObjectWithFile:storedScoresFilename];
    
    if (unarchivedObj) {
        storedScores = [[NSMutableArray alloc] initWithArray:unarchivedObj];
        [self resubmitStoredScores];
    } else {
        storedScores = [[NSMutableArray alloc] init];
    }
}


// Save stored scores to file.
- (void)writeStoredScore
{
    [writeLock lock];
    NSData * archivedScore = [NSKeyedArchiver archivedDataWithRootObject:storedScores];
    NSError * error;
    [archivedScore writeToFile:storedScoresFilename options:NSDataWritingFileProtectionNone error:&error];
    if (error) {
        //  Error saving file, handle accordingly
    }
    [writeLock unlock];
}

// Store score for submission at a later time.
- (void)storeScore:(GKScore *)score
{
    [storedScores addObject:score];
    [self writeStoredScore];
}

// Attempt to submit a score. On an error store it for a later time.
- (void)submitScore:(GKScore *)score
{
    if ([GKLocalPlayer localPlayer].authenticated) {
        if (!score.value) {
            // Unable to validate data.
            return;
        }
        
        // Store the scores if there is an error.
        [score reportScoreWithCompletionHandler:^(NSError *error){
            if (!error || (![error code] && ![error domain])) {
                // Score submitted correctly. Resubmit others
                [self resubmitStoredScores];
            } else {
                // Store score for next authentication.
                [self storeScore:score];
            }
        }];
    }
}

@end
